<template>
  <div>
    <div class="top-panel__box">
      <el-form :model="dataForm" ref="dataForm" inline size="small" onsubmit="return false">
        <el-row>
          <el-col :span="24" style="margin-bottom:15px;">
            <el-form-item label="产品类型" label-width="80px">
                <el-select placeholder="产品类型" v-model="dataForm.productTypeList" multiple clearable collapse-tags>
                  <el-option v-for="(value, key) of dicts['product_type'].childMap" :key="key" :label="value" :value="key" />
                </el-select>
              </el-form-item>
            <el-form-item>
              <el-input placeholder="输入借款编号/姓名" v-model="dataForm.freeCondition" maxlength="30" clearable />
            </el-form-item>
            <el-form-item>
              <el-input placeholder="受理人" v-model="dataForm.acceptorName" maxlength="30" clearable />
            </el-form-item>
            <el-form-item>
                <el-date-picker type="date" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd" v-model="dataForm.beginTime" style="width:220px" placeholder="申请时间起" />
                <span>-</span>
                <el-date-picker type="date"  @change="endChange" v-model="dataForm.endTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width:220px" placeholder="申请时间止" />
              </el-form-item>
            <el-form-item label="全部状态" label-width="80px">
                <el-select placeholder="全部状态" v-model="dataForm.researchStatus" clearable>
                  <el-option v-for="(value, key) in dicts['research_status'].childMap" :key="key" :label="value" :value="key" />
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item>
              <el-button type="primary" @click="getList(1)">
                <fa-icon class="fa-search" />查询</el-button>
              <reset-button :dataForm.sync="dataForm" :fixedData="{pageNum: 1, pageSize: 10}" />
              <el-button type="primary" @click="batchAssign('cancel')">批量撤回</el-button>
              <el-button type="primary" @click="batchAssign('assign')">批量分派</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-row class="table-top">
      <el-table :border="true" :row-key="getRowKey" @select-all="selectAllEvent" :data="dataList" v-loading="tableLoading" tooltip-effect="light" @selection-change="handleSelectionChange" :cell-style="addCellStyle" class="tc-table-box" size="small">
        <el-table-column type="selection" width="55" fixed="left"></el-table-column>
        <el-table-column type="index" width="55" fixed="left" label="序号"></el-table-column>
        <template v-for="(column, index) in FOLLOW_HEAD_LIST">
          <el-table-column :prop="column.prop" :label="column.label" :key="index" :width="column.width" :show-overflow-tooltip="true" />
        </template>
        <el-table-column fixed="right" class-name="oper-col" width="100" label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" plain @click="apportionEvent(scope.row, 'PROCESSING')" v-if="scope.row.acceptorName && scope.row.researchStatus != 'COMPLETED'">
                撤回
              </el-button>
              <el-button type="primary" size="mini" plain @click="apportionEvent(scope.row, 'WAIT_ASSIGN')" v-if="!scope.row.acceptorName && scope.row.researchStatus != 'COMPLETED'">
                分派
              </el-button>
              <el-button type="primary" size="mini" plain @click="showDetails(scope.row)" v-if="scope.row.acceptorName && scope.row.researchStatus === 'COMPLETED'">
                详情
              </el-button>
            </template>
        </el-table-column>
      </el-table>
      <el-row class="pagination-top">
        <pagination :pageNum.sync="dataForm.pageNum" :curSizes.sync="dataForm.pageSize" :total="total" @getList="getList" />
      </el-row>
    </el-row>
    <!--编辑-->
    <el-dialog title="分派" :visible.sync="showWaitAssign" width="45%" :close-on-click-modal="false">
      <wait-assign v-if="showWaitAssign" @updataSuccess="getWaitAssigner" @close="closeLoanDetail"></wait-assign>
    </el-dialog>
    <el-dialog title="详情" :visible.sync="showDetailsDialog" width="65%" :close-on-click-modal="false">
      <before-lending-details v-if="showDetailsDialog" :researchId="nowResearchId" :caseId="nowCaseId" :productType="productType" @close="closeDetails"></before-lending-details>
    </el-dialog>
  </div>
</template>

<script>
import api from './api'
import { CONSTANT_OBJ } from '@/utils/constant'
import { mapState } from 'vuex'
import { FOLLOW_HEAD_LIST } from './js/contant.js'
import OrganizationCascader from '@/components/organizationCascader'
import WaitAssign from './components/WaitAssign'
import BeforeLendingDetails from './components/BeforeLendingDetails'
import { common } from '@/utils/common'
import { disposePhone, encryptName } from '@/utils/util'
export default {
  components: {OrganizationCascader, WaitAssign, BeforeLendingDetails},
  data () {
    return {
      FOLLOW_HEAD_LIST,
      tableLoading: false,
      showWaitAssign: false,
      showDetailsDialog: false,
      selectIds: [],
      slectedList: [],
      nowCaseId: '',
      nowResearchId: '',
      dataForm: {
        acceptorName: '',
        beginTime: '',
        endTime: '',
        customerName: '',
        productTypeList: [],
        researchStatus: '',
        freeCondition: '',
        pageNum: 1,
        pageSize: 10
      },
      dataList: [],
      editorDialog: false,
      total: 0,
      productNoList: [],
      editData: {},
      uploadDialog: false,
      productType:''
    }
  },
  mounted () {
    this.getList()
    console.log('this.dicts', this.dicts)
  },
  methods: {
    // 查询列表
    getList (val) {
      if (!this.rulesTime()) return
      this.dataForm.pageNum = val || this.dataForm.pageNum
      this.tableLoading = true
      api.queryResearchByCondition(this.dataForm).then(res => {
        const { responseCode, data } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.dataList = [...data.list] || []
          console.log(this.dataList)
          this.dataList.forEach(item => {
            let statusUpdateTime = new Date(item.statusUpdateTime).getTime()
            let newTime = new Date().getTime()
            let statusStopTime = `${parseInt((newTime - statusUpdateTime) / 60000)}min`
            item.statusStopTime = statusStopTime
            item.newPhone = disposePhone(item.customerPhone)
            item.newName = encryptName(item.customerName)
          })
          this.dataList = [...this.disoseStatus(this.dataList)]
          console.log(this.dataList)
          this.total = parseInt(data.total) || 0
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    /**
    * @description 当前状态停留时间：若大于60min，则标记为红色
    */
    addCellStyle ({ row: { statusStopTime }, column: { property } }) {
      if (parseInt(statusStopTime) > 60 && property === 'statusStopTime') {
        return 'color: red'
      }
    },
    disoseStatus (list) {
      return list.map(ele => {
        this.dicts.research_status.childList.forEach(v => {
          if (ele.researchStatus === v.dictNo) {
            ele.newStatus = v.dictName
          }
        })
        this.dicts.product_type.childList.forEach(v => {
          if (ele.productType === v.dictNo) {
            ele.newProductType = v.dictName
          }
        })
        return ele
      })
    },
    handleSelectionChange (row) {
      console.log(row)
      this.slectedList = row
      let ids = this.slectedList.map(ele => ele.researchId)
      this.selectIds = [...ids]
    },
    showEditor (row) {
      this.editorDialog = true
      this.editData = {...row}
    },
    close (data) {
      console.log(data)
      this.editorDialog = data
    },
    enterPersonInfo () {
      common.confirmFn('', '是否确认分派代理人').then(res => {
        if (res) {
          console.log('确认成功')
        }
      })
    },
    deletPersonInfo () {
      common.confirmFn('撤回后您可重新进行分派', '是否确定撤回分派？').then(res => {
        if (res) {
          console.log('删除成功')
          api.cancelResearch({researchIds: this.selectIds}).then(res => {
            this.successFn(res)
          })
        }
      })
    },
    showUpload () {
      this.uploadDialog = true
    },
    closeUpload (res) {
      this.uploadDialog = res
    },
    showDetails (item) {
      this.nowCaseId = item.caseId
      this.nowResearchId = item.researchId
      this.productType = item.productType
      console.log(item, '内容')
      // return
      this.showDetailsDialog = true
    },
    closeDetails (val) {
      this.showDetailsDialog = false
    },
    apportionEvent (item, type) {
      this.selectIds = [item.researchId]
      switch (type) {
        case 'WAIT_ASSIGN':
          this.showWaitAssign = true
          break
        case 'PROCESSING':
          this.deletPersonInfo()
          break
      }
    },
    /**
     * @description 批量分派/撤回
     */
    batchAssign (type) {
      if (this.selectIds.length === 0) {
        this.$message.error('请选择至少一份案件')
        return
      }
      switch (type) {
        case 'assign':
          this.disposeBatchData()
          break
        case 'cancel':
          this.disposeCancelData()
          break
      }
    },
    disposeCancelData () {
      let ids = this.filterData(this.slectedList)
      console.log(ids, '数据处理')
      if (ids.failIndex > 0) {
        common.confirmFn(`当前已选中进件 ${this.slectedList.length} 笔，其中可撤回分派进件 ${ids.failIndex} 笔。`, '是否确定批量撤回分派？').then(res => {
          if (res) {
            api.cancelResearch({researchIds: ids.failIds}).then(res => {
              this.successFn(res)
            })
          }
        })
      } else {
        common.confirmFn(`当前选中的进件中无可撤回分派进件。`, '无可撤回进件').then(res => {
          if (res) {}
        })
      }
    },
    disposeBatchData () {
      let ids = this.filterData(this.slectedList)
      if (ids.successIndex > 0) {
        common.confirmFn(`当前已选中进件 ${this.slectedList.length} 笔，其中可分派进件 ${ids.successIndex} 笔。`, '是否确定批量分派？').then(res => {
          if (res) {
            this.selectIds = [...ids.successIds]
            this.showWaitAssign = true
          }
        })
      } else {
        common.confirmFn(`当前选中的进件中无可分派进件。`, '无可分派进件').then(res => {
          if (res) {}
        })
      }
    },
    selectAllEvent (selection) {
      this.slectedList = [...selection]
    },
    // 处理数据
    filterData (ids) {
      let checked = ids.filter(v => v.researchStatus !== 'COMPLETED' && !v.acceptorName)
      let notCheck = ids.filter(v => v.researchStatus !== 'COMPLETED' && v.acceptorName)
      console.log(checked, '可分派')
      console.log(notCheck, '不可分派')
      let successIndex = checked.length
      let failIndex = notCheck.length
      let successIds = checked.map(ele => ele.researchId)
      let failIds = notCheck.map(ele => ele.researchId)
      return {
        successIndex,
        failIndex,
        failIds,
        successIds
      }
    },
    getWaitAssigner (val) {
      console.log(val, '获取分派人')
      let params = {
        acceptorId: val,
        researchIds: [...this.selectIds]
      }
      console.log(params, '分派受理人')
      api.assignAcceptor(params).then(res => {
        this.successFn(res, 'showWaitAssign')
      })
    },
    successFn (res, dialog) {
      const { responseCode, responseMsg: message } = res
      if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
        this.$message({
          message,
          type: 'success'
        })
        if (dialog) {
          this[dialog] = false
        }
        this.selectedIds = []
        this.slectedList = []
        this.getList(1)
      }
    },
    closeLoanDetail (val) {
      this.showWaitAssign = val
    },
    endChange (end) {
      this.dataForm.endTime = end == null ? end : `${end} 23:59:59`
    },
    getRowKey (row) {
      return row.researchId
    },
    rulesTime () {
      let tempStart = this.dataForm.beginTime
      let tempEnd = this.dataForm.endTime
      let start = new Date(tempStart).getTime() || ''
      let end = new Date(tempEnd).getTime() || ''
      if (start && end) {
        if (start > end) {
          this.$message.error('结束时间不能小于开始时间')
          return false
        } else {
          return true
        }
      }
      return true
    }
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    })
  }
}
</script>
<style lang="less">
@import '../../assets/css/common.less';
.tc-table-box {
  border: 1px solid @main-border-color;
  border-bottom: none;
  width:100%;
}

.el-table-box thead{
  color: #707277;
}
.tc-table-box th{
  background-color: @panel-color !important;
}
</style>
